package beanstao.util.j2ee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import beanstao.util.Encoding;
import beanstao.util.log.LogHelper;
import beanstao.util.response.PD;


/**
 * 一个针对Http相关的助手类
 * 
 * @author beanstao@google.com 
 */
public class Https
{
	private static Https logObject = new Https();

	/**
	 * 当Request处理完成后，向浏览器返回信息的动作方法
	 * 
	 * @param response 浏览器接收信息的封装
	 * @param data 将要被返回的信息的封装类型
	 */
	public static void responsePrint(final HttpServletResponse response, final PD data)
	{
		String info = "";
		if ((data.$Data() != null) && (data.$Data() instanceof Boolean))
			info = String.valueOf(data.$Data());
		info = data.toJson();
		responsePrint(response, info);
	}

	/**
	 * 当Request处理完成后，向浏览器返回信息的动作方法
	 * 
	 * @param response 浏览器接收信息的封装
	 * @param info 将要被返回的信息
	 */
	public static void responsePrint(final HttpServletResponse response, String info)
	{
		PrintWriter printWriter = null;
		try
		{
			response.setCharacterEncoding(Encoding.UTF8);
			printWriter = response.getWriter();
		}
		catch (IOException e)
		{
			LogHelper.logWarn(logObject, "异常。HttpServletResponse中无法获取PrintWriter，应向浏览器发送" + info, e);
		}
		printWriter.println(info);
		printWriter.flush();
		printWriter.close();
		LogHelper.logDebug(logObject, "传值:" + info);
	}

	/**
	 * 当Request处理完成后，向浏览器返回信息的动作方法
	 * 
	 * @param response 浏览器接收信息的封装
	 * @param info 将要被返回的信息,虽然是Object，但方法内部仅处理ResponseData和String两种类型
	 */
	public static void responsePrint(final HttpServletResponse response, final Object info)
	{
		if (info instanceof String)
			responsePrint(response, (String) info);
		else if (info instanceof PD)
			responsePrint(response, (PD) info);
		else
			responsePrint(response, info.toString());
	}
}
